import Config from './config.js'
import CryptoJS from './crypto.js';
import md5 from './md5.js';
import Base64 from './base64.min.js'
// import Util from './util.js'

export default {
	components: {
		CryptoJS
	},
	sendRequest(params) {
		if(params.method != undefined){
			var method = params.method;
		}else{
			var method = 'GET';
		}
		// var url = Config.baseUrl + '/appapi?service=' + params.url; // 请求路径
		var url = Config.baseUrl + '/appapi?'; // 请求路径
		var data = {};
		// token
		// if (uni.getStorageSync('token')) data.token = uni.getStorageSync('token');
		
		// 将对象的键按照字母顺序排序
		const sortedKeys = Object.keys(params.data).sort();
		
		// 使用map方法将键值对拼接成key=value形式的字符串
		var queryString = sortedKeys.map(key => `${key}=${params.data[key]}`).join('&');
		// 请求参数加密
		if (Config.apiSecurity) {
			var arr = this.sort(params.data);
			let resultString = Object.values(arr);
			let value = resultString.join('');
			let values = value + Config.salt;
			var sign = md5(values);
			queryString += '&new_sign=' + sign + '&__RESPONSE_NOT_ENCRYPT_NANYU__=1';
			url += queryString;
		}
		if (params.data != undefined) Object.assign(data, params.data);
		if (params.async === false) {
			//同步
			return new Promise((resolve, reject) => {
				uni.request({
					url: url,
					method: method,
					data: data,
					header: params.header || {
						'content-type': 'application/x-www-form-urlencoded;application/json'
					},
					dataType: params.dataType || 'json',
					responseType: params.responseType || 'text',
					success: (res) => {
						// var param = JSON.parse(this.decrypt(res.data));
						// resolve(param);
						resolve(res.data);
					},
					fail: (res) => {
						reject(res);
					},
					complete: (res) => {
						reject(res);
					}
				});
			});
		} else {
			//异步
			uni.request({
				url: url,
				method: method,
				data: data,
				header: params.header || {
					'content-type': 'application/x-www-form-urlencoded;application/json'
				},
				dataType: params.dataType || 'json',
				responseType: params.responseType || 'text',
				success: (res) => {
					// var param = JSON.parse(this.decrypt(res.data));
					typeof params.success == 'function' && params.success(res.data);

					// console.log(JSON.parse(param));return;
					// typeof params.success == 'function' && params.success(res.data);
				},
				fail: (res) => {
					typeof params.fail == 'function' && params.fail(res);
				},
				complete: (res) => {
					typeof params.complete == 'function' && params.complete(res);
				}
			});
		}
	},
	// 解密
	decrypt(encryptedData) {
		// 解密密钥和偏移量（IV）
		const key = CryptoJS.enc.Utf8.parse(Config.key);
		const iv = CryptoJS.enc.Utf8.parse(Config.iv);

		// 将Base64编码的数据解码为WordArray对象
		const ciphertext = CryptoJS.enc.Base64.parse(encryptedData);

		// 解密过程
		const decrypted = CryptoJS.AES.decrypt({
				ciphertext
			},
			key, {
				iv,
				mode: CryptoJS.mode.CBC,
				padding: CryptoJS.pad.Pkcs7
			}
		);

		// 将解密后的WordArray对象转换为UTF-8字符串
		const decryptedText = CryptoJS.enc.Utf8.stringify(decrypted);
		// console.log(decryptedText)
		return decryptedText;
	},
	// 排序
	sort(obj) {
		var arr = new Array();
		var num = 0;
		for (var i in obj) {
			arr[num] = i;
			num++;
		}
		var sortArr = arr.sort();
		// var sortArr = arr.sort().reverse();
		var sortObj = {};
		for (var i in sortArr) {
			sortObj[sortArr[i]] = obj[sortArr[i]];
		}
		return sortObj;
	},
	ksort(obj) {
		var arr = new Array();
		var num = 0;
		for (var i in obj) {
			arr[num] = i;
			num++;
		}
		// var sortArr = arr.sort();
		var sortArr = arr.sort().reverse();
		var sortObj = {};
		for (var i in sortArr) {
			sortObj[sortArr[i]] = obj[sortArr[i]];
		}
		return sortObj;
	},
	sortMap(map, ascOrDesc = true) {
		let keys = new Array()
		for (let key of map.keys()) {
			keys.push(key)
		}
		if (ascOrDesc) {
			keys.sort(function(a, b) {
				if (a.length == b.length) {
					return a.localeCompare(b);
				} else {
					return a.length - b.length;
				}
			})
		} else {
			keys.sort(function(a, b) {
				if (a.length == b.length) {
					return b.localeCompare(a);
				} else {
					return b.length - a.length;
				}
			})
		}
		let newMap = new Map()
		keys.forEach(key => {
			newMap.set(key, map.get(key))
		})
		return newMap;
	},
	group(array, subGroupLength) {
	    let index = 0;
	    let newArray = [];
	    while(index < array.length) {
	        newArray.push(array.slice(index, index += subGroupLength));
	    }
	    return newArray;
	},
	levelimg(levelid = null){
		if(levelid == null){
			return '';
		}
		let config = uni.getStorageSync('config');
		let level = config['level'];
		let result = level.filter(item => item.levelid == levelid);
		return result[0]['thumb'];
	},
	levelanchorimg(levelanchor){
		if(levelanchor == null){
			return '';
		}
		let config = uni.getStorageSync('config');
		let level_anchor = config['levelanchor'];
		let result = level_anchor.filter(item => item.levelid == levelanchor);
		return result[0]['thumb'];
	},
	checklogin(url = '/pages/index/index'){
		let uid = uni.getStorageSync('uid');
		if(uid){
			this.sendRequest({
				data:{
					service:'User.getBaseInfo',
					uid:uni.getStorageSync('uid'),
					token:uni.getStorageSync('token'),
				},
				success: res => {
					if(res.data.code == 0){
					}else{
						// var msg = res.msg == '' ? res.data.msg : res.msg;
						uni.showModal({
							title: '提示',
							content: '您的登陆状态失效，请重新登陆！',
							showCancel:false,
							success: function (res) {
								if (res.confirm) {
										uni.redirectTo({
											url: "/pages/login/login?url="+url,
										})
								}
							}
						});
						
					}
				}
			});
		}
	}
}